package Servlet;

import Entity.Clue;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Clara
 */
public class CluesServlet extends HttpServlet {

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("clues", getClues(Integer.parseInt(request.getParameter("level"))));
        
        // Now that the controller has gathered the data from the model,
        // pass the data onto the view to render it as JSON.
        RequestDispatcher view = request.getRequestDispatcher("/clues_view.jsp");
        view.forward(request, response);
    }

    private List<Map<String, String>> getClues(int level) {
        List<Map<String, String>> clues = new ArrayList<Map<String, String>>();

        try {
            //get context from context file.
            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            //find clue by level number.
            Query q = em.createNamedQuery("Clue.findByLevelNo").setParameter("levelNo", level);
            List<Clue> results = q.getResultList();
            //build list of maps from clues.
            for (Clue c : results) {
                Map<String, String> clue = new HashMap<String, String>();
                clue.put("id", "" + c.getCluePK().getClueNo());
                clue.put("description", c.getClue());
                clues.add(clue);
            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        return clues;
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
